home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C# & Game Programming - A…er's Guide (2nd Edition)
/
Buono 2nd Ed.iso
/
GameClasses
/
GameTimer.cs
< prev
next >
Wrap
Text File
|
2004-09-07
|
3KB
|
77 lines
using System;
using System.Windows.Forms;
using System.Collections;
namespace GameClasses {
public class GameTimer {
// Member fields
Timer gameTimer; // main timer object
int baseInterval; // base interval in ms
Hashtable events; // list of TimedEvent objects
// Default constructor
public GameTimer(int interval) {
events = new Hashtable();
gameTimer = new Timer();
gameTimer.Interval = interval;
gameTimer.Tick += new EventHandler(Tick);
baseInterval = interval;
}
// Simple start and stop functionality.
public void Start() {gameTimer.Start();}
public void Stop() {gameTimer.Stop();}
// Add an event to our game timer. Use stepFactor to control the
// frequency the given TimedEvent's Tick() will be called.
// Use the given "key" for future reference to this TimedEvent.
public void addEvent(TimedEvent timedEvent, int stepFactor,
string key) {
TimedEventNode node = new TimedEventNode();
node.data = timedEvent;
node.timeStep = stepFactor;
node.stepCount = 0;
events.Add(key, node);
}
// Returns the event marked with the given key
public TimedEvent getEvent(string key) {
return ((TimedEventNode) events[key]).data;
}
// Removes an event from the list
public void removeEvent(string key) {
events.Remove(key);
}
// Changes the step associated with the event indexed by key
public void ChangeStep(string key, int stepFactor) {
((TimedEventNode) events[key]).timeStep = stepFactor;
}
// Tick() -- passes on tick event to proper TimedEvent objects
public void Tick(object sender, EventArgs e) {
IDictionaryEnumerator itemEnumerator = events.GetEnumerator();
TimedEventNode node;
while (itemEnumerator.MoveNext()) {
node = (TimedEventNode) itemEnumerator.Value;
if (node.stepCount >= node.timeStep) {
node.stepCount = 0;
node.data.Tick();
} else {
node.stepCount++;
}
}
}
// Helper class to hold a extra information relevant to
// timer event processing.
class TimedEventNode {
public int timeStep; // how many baseInterval ticks to wait
public int stepCount; // counter to compare with timeStep
public TimedEvent data; // the TimedEvent object
}
}
}